#include "Precomp.h"
#include "Renderer.h"
#include "Map.h"

bool Layer::xSort(const ShapeType a, const ShapeType b)
{
	return (a->shape->GetPosition().x<b->shape->GetPosition().x);
}

bool Layer::ySort(const ShapeType a, const ShapeType b)
{
	return (a->shape->GetPosition().y<b->shape->GetPosition().y);
}

Layer::Layer(const SQChar* name)
:name(name),sortType(VERTICAL)
{
}

void Layer::clear()
{
	shapes.clear();
}

void Layer::render(sf::RenderWindow& window)
{
	switch(sortType)
	{
	case HORIZONTAL:
		shapes.sort(xSort);
	break;
	case VERTICAL:
		shapes.sort(ySort);
	break;
	};
	for(std::list<ShapeType>::iterator i=shapes.begin();i!=shapes.end();++i)
	{
		const sf::Drawable& draw=*((*i)->shape);
		window.Draw(draw);
		if((*i)->getDebug())
		{
			sf::Shape bbox=sf::Shape::Rectangle(0,0,draw.GetScale().x*(*i)->size.x,draw.GetScale().y*(*i)->size.y,sf::Color::Blue,2,sf::Color::Blue);
			bbox.EnableFill(false);
			bbox.EnableOutline(true);
			bbox.SetCenter(draw.GetCenter());
			bbox.SetPosition(draw.GetPosition());
			bbox.SetRotation(draw.GetRotation());
			window.Draw(bbox);
		}
	}
}

void Layer::addShape(ShapeType shape)
{
	shapes.push_back(shape);
}

void Layer::removeShape(ShapeType shape)
{
	shapes.remove(shape);
}

const SQChar* Layer::getName() const
{
	return name.c_str();
}

void Layer::setName(const SQChar* newName)
{
	name=newName;
}

void Layer::setSortType(SortType type)
{
	sortType=type;//TODO: set sort type
}

//Renderer
Renderer::Renderer(sf::RenderWindow& renderWindow)
:window(renderWindow)
{
}

void Renderer::render()
{
	for(std::vector<Layer*>::iterator i=map->layers.begin();i!=map->layers.end();++i)
	{
		(*i)->render(window);
	}
}

const sf::View& Renderer::getCurrentView() const 
{
	return window.GetView();
}

void Renderer::setView(const sf::View& view)
{
	window.SetView(view);
}

void Renderer::setMap(Map* map)
{
	this->map=map;
}